Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
Function to return digits from a string, if length >= 4

This function is retrieving the last numbers of a string:

function getLastNumberOfString(str){
  var allNumbers = str.replace(/[^0-9]/g, ' ').trim().split(/\s+/);
  return parseInt(allNumbers[allNumbers.length - 1], 10);
}

I want it to retrieve the last numbers of a string, if it contains at least 4 digits.

For example:

"1234-string-text/8177-1-3-tools-for-knowledge.html"

Is returning:

3

I'd like it to return:

8177
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

To match last set of numbers containing at least 4 digits use:

\d{4,}(?!.+\d{4})

RegEx Demo

RegEx Details:

  • \d{4,}: Match 4 or more digits
  • (?!.+\d{4}): Negative Lookahead to assert that there is no other occurrence of 4 digit numbers ahead

Code:

function getLastNumberOfString(str){
  var m = str.match(/\d{4,}(?!.+\d{4})/);
  return (m ? parseInt(m[0]) : NaN);
}

console.log(getLastNumberOfString("1234-string-text/8177-1-3-tools-for-knowledge.html"));

console.log(getLastNumberOfString("tools-for-knowledge.html"));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!